<template>
  <div class="outSuppleDetail">
    <div style="margin-bottom: 10px">
      <jc-button
        :btn-arr="['save', 'remove', 'pass', 'sub', 'option', 'reload', 'list', !list.length && 'check']"
        :disab-arr="['close', 'cancel', 'toExcel', 'using', 'freeze']"
        :fbillno="production.fbillNo"
        :list="'/outSupplement'"
        @refresh="getSCLLinfo"
        @save="proSave"
        @submit="proSave(1)"
        @noSubmit="submit(2)"
        @audit="audit(1)"
        @noAudit="audit(2)"
        @del="handleDelete"
        @handleCom1="handleCom('1')"
        @handleCom2="handleCom('2')"
        @check="check('up')"
        @check1="check('down')"
      />
    </div>
    <el-tabs v-model="activeName" @tab-click="handleOther">
      <el-tab-pane :label="$t('market.info')" name="first">
        <el-form ref="purchaseRef" :model="production" label-width="4.68vw">
          <el-form-item :label="$t('market.documentstatus')">
            <el-tag :type="production.stateColor">{{ production.fdocumentstatus }}</el-tag>
          </el-form-item>
          <el-form-item :label="$t('market.billNo')">
            <el-input v-model.trim="production.fbillNo" disabled />
          </el-form-item>
          <el-form-item :label="$t('market.picker')">
            <el-input v-model.trim="production.fpicker" :disabled="isDisabled">
              <i
                slot="suffix"
                class="el-input__icon el-icon-search"
                @click="userVisiblit = true"
              />
            </el-input>
          </el-form-item>
          <el-form-item :label="$t('market.stocker')">
            <el-input v-model.trim="production.fstockerName" :disabled="isDisabled">
              <i
                slot="suffix"
                class="el-input__icon el-icon-search"
                @click="openStocker=true"
              />
            </el-input>
          </el-form-item>
          <el-form-item :label="$t('market.fdate')">
            <el-date-picker
              v-model="production.fdate"
              type="date"
              value-format="yyyy-MM-dd"
              size="mini"
              :disabled="isDisabled"
            />
          </el-form-item>
          <!--          <el-form-item label="委外组织">-->
          <!--            <el-input v-model.trim="production.fsuborg" disabled />-->
          <!--          </el-form-item>-->
          <!--          <el-form-item label="结算组织">-->
          <!--            <el-input v-model.trim="production.fsettleorg" disabled />-->
          <!--          </el-form-item>-->
          <el-form-item :label="$t('market.note')">
            <el-input v-model.trim="production.fremark" :disabled="isDisabled" />
          </el-form-item>
        </el-form>
        <div>
          <div>
            <el-button size="mini" disabled>{{ $t('btn.newHang') }}<!--新增行--></el-button>
            <el-button size="mini" style="margin-bottom: 5px;" @click="delHang">{{ $t('btn.delHang') }}<!--删除行--></el-button>
          </div>
          <jc-table
            :table-data="tableData"
            :table-header="tableHeard"
            :table-height="tableHeight"
            :get-summaries="getSummaries"
            show-summary
            @rowClick="rowClick"
          >
            <!--物料编码-->
            <template v-slot:orderSlot="col">
              <el-link type="primary" @click="sonJumpMateriel(col.scope.row.fnumber)">
                {{ col.scope.row.fnumber }}
              </el-link>
            </template>
            <!--实发数量-->
            <template v-slot:btnSlot="col">
              <el-input-number
                v-model="col.scope.row.factualQty"
                :disabled="isDisabled"
                :min="0"
                :max="Number(col.scope.row.fappQty)"
                size="mini"
              />
            </template>
            <!--库位-->
            <template v-slot:text3Slot="col">
              <el-select v-model="col.scope.row.finpositionid" size="mini" @change="handelCode1(col.scope.$index)">
                <el-option v-for="item in col.scope.row.codes" :key="item.fid" :label="item.positionfnumber" :value="item.fpositionid" />
              </el-select>
            </template>
            <!-- 仓库-->
            <template v-slot:billSlot="col">
              <el-input
                v-model="col.scope.row.fstockName"
                size="mini"
                :disabled="isDisabled"
              >
                <i
                  slot="suffix"
                  class="el-input__icon el-icon-search"
                  @click="handleWarehouse(col.scope.$index)"
                />
              </el-input>
            </template>
          </jc-table>
        </div>
      </el-tab-pane>
      <el-tab-pane :label="$t('market.other')" name="log">
        <jc-marker
          ref="log"
          :fnumber="production.fbillNo"
          other-height="68vh"
          :other-url-object="otherUrlObject"
        />
      </el-tab-pane>
    </el-tabs>
    <!--    仓管员-->
    <stocker v-if="openStocker" @stocker="stockerData" />
    <!--申请人-->
    <user v-if="userVisiblit" @supplier="selectApply" />
    <selectCK v-if="seleceVisiblit" :fmaterial-id="stockFnumber" @client="selectData" />
    <upDown v-if="upDownVis" :msg="cha" :fentryid="fentryData" @client="upDownVis=false" />
  </div>
</template>

<script>
import { querySubRepairDetails } from '@/api/production/productionList'
import { toMxBmina } from '@/components/ToMxamineState'
import jcButton from '@/components/Button'
import jcMarker from '@/components/marker'
import {
  auditSubReturnmtrls, delSubReturnmtrls,
  notsubmitSubReturnmtrl,
  submitSubReturnmtrl, unauditSubReturnmtrls,
  updateSubPickmtrlDetails
} from '@/api/production/productionPicking'
import jumpMateriel from '@/components/JumpMateriel'

export default {
  components: {
    user: () => import('@/views/basic/users/userslist/component/user'),
    stocker: () => import('@/views/purchasing/putStorage/editStorage/component/stocker'),
    selectCK: () => import('@/views/production/collect/components/seleceCK'),
    jcButton,
    jcMarker
  },
  mixins: [jumpMateriel],
  props: {
    list: {
      type: Array,
      default: function() {
        return []
      }
    }
  },
  data() {
    return {
      upDownVis: false,
      openStocker: false,
      userVisiblit: false,
      cha: '',
      fentryData: [],
      isDisabled: false,
      seleceVisiblit: false, // 仓库
      activeName: 'first',
      stockFnumber: '',
      production: {},
      tableAudit: [],
      tableHeight: '73vh',
      otherUrlObject: {},
      tableData: [],
      delArr: [],
      tableHeard: [
        { label: this.$t('market.fseq'), prop: 'fseq', width: '80' },
        { label: this.$t('market.outPickSeq'), prop: 'ppbomentrySeq', width: '80' },
        { label: this.$t('market.outproEdit'), prop: 'ppbomBillNo', minWidth: '100px' },
        { label: this.$t('market.fmaterial'), prop: 'fnumber', type: 'order', width: '120px' },
        { label: this.$t('market.fmodel'), prop: 'fmodel' },
        { label: this.$t('market.fdescripTion'), prop: 'fdescripTion', minWidth: '220px' },
        { label: this.$t('shop.fspecificaTion'), prop: 'fspecificaTion', minWidth: '130px' },
        { label: this.$t('market.appQty'), prop: 'fappQty', width: '80px' },
        { label: this.$t('market.realqty'), type: 'btn', prop: 'factualQty', width: '80px' },
        { label: this.$t('market.stock2'), prop: 'fstockName', minWidth: '100px' }, // type: 'bill',
        { label: this.$t('market.stockQty'), prop: 'stockQty', width: '80' },
        { label: this.$t('market.storageLoca'), type: 'text3', prop: 'fcodefnumber', width: '130' },
        { label: this.$t('market.storageQty'), prop: 'fcodeQty', width: '80' },
        { label: this.$t('market.salKhddh'), prop: 'salKhddh' },
        { label: this.$t('market.suppliername'), prop: 'fsupplierName' },
        { label: this.$t('market.outOdd'), prop: 'fmobillNo' },
        { label: this.$t('market.outCollectSeq'), prop: 'fmoentrySeq', width: '80' }
        // { label: '入库组织', prop: 'fstockorg' },
        // { label: '货主', prop: 'fowner' }
      ]
    }
  },
  created() {
    if (this.$route.params.id) {
      this.getSCLLinfo()
    }
    this.tableHeight = window.innerWidth > 1440 ? 'calc(100vh - 260px)' : '73vh'
  },
  methods: {
    // 补料单详情数据
    getSCLLinfo() {
      const DATA = {
        fid: this.$route.params.id
      }
      querySubRepairDetails(DATA).then(res => {
        if (res.code === 0) {
          this.production = toMxBmina(res.data)
          this.tableData = res.data.details
          this.tableData.map(res => {
            res.finpositionid = res.codes?.[0]?.fpositionid
            res.fcodeQty = res.codes?.[0]?.fqty || 0
          })
          this.otherUrlObject = res.data
          this.isDisabled = this.production.fdocumentstatus === this.$t('market.state1') || this.production.fdocumentstatus === this.$t('market.state2')
        } else {
          this.$message.error(res.message)
        }
      })
    },
    // 保存
    proSave(ev) {
      this.tableAudit = []
      this.tableData.forEach(item => {
        this.tableAudit.push({
          funitId: item.funitId,
          fstockId: item.fstockId,
          fentryId: item.fentryId,
          factualQty: item.factualQty
        })
      })
      const { fid, fdate, fremark, fstockerId, fpickerId } = this.production
      const DATA = {
        fid,
        fdate,
        fremark, fstockerId, fpickerId,
        delArr: this.delArr,
        details: this.tableAudit
      }
      updateSubPickmtrlDetails(DATA).then(res => {
        if (res.code === 0) {
          ev === 1 ? this.submit(1) : this.getSCLLinfo()
          this.$message({ showClose: true, message: res.message, type: 'success' })
        } else {
          this.$message.error(res.message)
        }
      })
    },
    // 打开仓库弹窗
    handleWarehouse(index) {
      this.indexSelf = index
      this.stockFnumber = this.tableData[index].fnumber
      this.seleceVisiblit = true
    },
    // 获取仓库数据
    selectData(ev) {
      if (ev.fstockId) {
        const item = this.tableData[this.indexSelf]
        item.fstockId = ev.fstockId
        item.fstockName = ev.fname
        item.stockQty = ev.sumQty
      }
      this.seleceVisiblit = false
    },
    // 仓管员
    stockerData(item) {
      if (item.fuserId) {
        this.production.fstockerId = item.fuserId
        this.production.fstockerName = item.fuserName
      }
      this.openStocker = false
    },
    // 领料人双击
    selectApply(item) {
      if (item.fuserId) {
        this.production.fpicker = item.fname
        this.production.fpickerId = item.fuserId
      }
      this.userVisiblit = false
    },
    // 公共函数
    toExamineFun(api, ev) {
      this.fentryData = []
      this.tableData.forEach(res => {
        this.fentryData.push(res.fentryId)
      })
      const DATA = {
        Numbers: [this.production.fbillNo],
        fIds: [this.production.fid],
        EntryIds: this.fentryData,
        entitys: ev === 1 ? this.entry : [],
        update: {
          delArr: this.delArr,
          ...this.production,
          details: this.tableData
        }
      }
      api(DATA).then(res => {
        if (res.code !== 0) {
          this.$confirm(res.message, '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'error'
          })
          return
        }
        this.getSCLLinfo()
        this.innerHTM = ''
        res.data.forEach(res => {
          this.innerHTM += '<div>' + res + '</div>'
        })
        this.$notify.warning({
          title: '提示',
          message: this.innerHTM,
          duration: 3000, offset: 50,
          dangerouslyUseHTMLString: true
        })
      })
    },
    // 提交
    submit(ev) {
      const api = ev === 1 ? submitSubReturnmtrl : notsubmitSubReturnmtrl
      this.toExamineFun(api)
    },
    // 审核
    audit(ev) {
      this.entry = []
      this.tableData.forEach(res => {
        this.entry.push({
          fsourcebillno: this.production.fbillNo,
          finpositionid: res.finpositionid,
          fmaterialid: res.fmaterialId,
          fmaterialnumber: res.fnumber,
          fmoentryid: res.fentryId,
          fqty: res.factualQty,
          funitid: res.funitId,
          isRaw: res.isRaw
        })
      })
      const api = ev === 1 ? auditSubReturnmtrls : unauditSubReturnmtrls
      this.toExamineFun(api, ev)
    },
    // 删除
    handleDelete() {
      if (this.isDisabled) {
        this.$confirm('请先反审核后再删除', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'error'
        })
        return
      }
      this.$confirm('此操作将永久删除该数据, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          const DATA = { Numbers: [this.production.fbillNo] }
          delSubReturnmtrls(DATA).then(res => {
            if (res.code === 0) {
              // 关闭当前页面
              this.$store.dispatch('tagsView/guanbi', this.$route)
              this.$router.replace({ path: '/outSupplement' })
            } else {
              this.$confirm(res.message, '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'error'
              })
            }
          })
        })
    },
    // 单击行
    rowClick(row) {
      this.indexSelf = row.index
    },
    // 删除行
    delHang() {
      const id = this.tableData[this.indexSelf].fentryId
      id && this.delArr.push(id)
      this.tableData.splice(this.indexSelf, 1)
    },
    // 操作记录
    handleOther(tab) {
      if (tab.name === 'log') {
        this.$refs.log.otherlog()
      }
    },
    // 上查、下查
    check(ev) {
      this.fentryData = []
      this.tableData.forEach(res => {
        this.fentryData.push(res.fentryId)
      })
      this.cha = ev
      this.upDownVis = true
    },
    // 套打
    handleCom(command) {
      const id = this.production.fbillNo
      if (command === '1') {
        this.$router.push({
          path: `/outSuppTong/${id}`
        })
      } else {
        this.$router.push({
          path: `/outSuppLian/${id}`
        })
      }
    }
  }
}
</script>
<style lang="scss" scope>
.outSuppleDetail {
  @include listBom;
  .el-tabs {
    .el-form {
      display: flex;
      flex-wrap: wrap;
      .el-input .el-input__inner {
        height: 30px;
        line-height: 30px;
      }
      .el-form-item {
        white-space: nowrap;
        overflow: hidden;
        text-overflow: ellipsis;
        height: 35px;
        width: 275px;
        min-width: 246px;
        margin-bottom: 0.46vh;
        .btnType {
          margin-right: 5px;
        }

        .el-date-editor.el-input {
          width: 100% !important;
        }

        .el-select {
          width: 100%;
        }
      }
    }
  }
}
</style>
